from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.schemas.user import UserCreate, UserResponse, UserCreateResponse, UserLoginRequest  # 明确导入模型
from app.services.user_service import UserService
from app.core.database import get_db
from app.core.local_logging import setup_logging
from app.core.jwt_utils import create_access_token
from datetime import timedelta
from app.core.encryption_utils import cipher  # 加密工具

logger = setup_logging()

router = APIRouter(prefix="/api/admin/users", tags=["用户管理"])

# 登录接口（改为JSON格式）
@router.post("/login")
async def login(user_data: UserLoginRequest, db: Session = Depends(get_db)):  # 改为使用UserLoginRequest模型
    user_service = UserService(db)
    # 验证用户（直接从JSON数据获取用户名密码）
    logger.debug(f"尝试登录用户: {user_data.username, user_data.password}")
    is_authenticated = user_service.authenticate(user_data.username, user_data.password)
    if not is_authenticated:
        raise HTTPException(status_code=200, detail="用户名或密码错误")
    
    # 生成 JWT 令牌
    access_token = create_access_token(
        data={"sub": user_data.username}
    )
    return {"code": 200, "message": "登录成功", "data": {"access_token": access_token}}

# 创建用户接口（使用 UserCreate 模型接收请求）
@router.post("", response_model=UserCreateResponse)  # 响应使用 UserCreateResponse 模型
async def create_new_user(user: UserCreate, db: Session = Depends(get_db)):
    logger.debug(f"尝试创建用户: {user.username}, {user.password}")
    user_service = UserService(db)
    created_user = user_service.create_user(user)
    if created_user:
        logger.info(f"用户创建成功: {created_user.username}")
        return {"message": "用户创建成功", "user": created_user}  # 符合 UserCreateResponse 结构
    # 用户名重复时返回标准错误格式
    raise HTTPException(
        status_code=400,
        detail=[{"loc": ["body", "username"], "msg": "用户名已存在", "type": "value_error"}]
    )

# 删除用户接口
@router.delete("/{username}")
async def remove_user(username: str, db: Session = Depends(get_db)):
    user_service = UserService(db)
    if user_service.delete_user(username):
        return {"message": "用户删除成功"}  # 符合 BaseResponse 模型
    raise HTTPException(status_code=404, detail="用户不存在")

# 获取所有用户接口（响应自动过滤密码）
@router.get("/ls", response_model=list[UserResponse])  # 直接使用 UserResponse 列表
async def get_all_users_list(db: Session = Depends(get_db)):
    user_service = UserService(db)
    return user_service.get_all_users()